package cn.com.ejiakanghu.task;

import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.TaskService;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.domain.LitemallOrderItem;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;

@Component
public class TaskStartupRunner implements ApplicationRunner {
    private Logger logger = LoggerFactory.getLogger(TaskStartupRunner.class);

    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private TaskService taskService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 从数据库捞出未支付订单
        List<LitemallOrder> orderList = orderService.queryUnpaid(SystemConfig.getOrderUnpaid());
        for(LitemallOrder order : orderList){
            LocalDateTime add = order.getAddTime();
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime expire =  add.plusMinutes(SystemConfig.getOrderUnpaid());
            if(expire.isBefore(now)) {
                // 已经过期，则加入延迟队列
                logger.debug("已经过期，则加入延迟队列 延迟为0");
                taskService.addTask(new OrderUnpaidTask(order.getId(), 0));
            }
            else{
                // 还没过期，则加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, expire);
                logger.debug("还没过期，则加入延迟队列 延迟为" + delay);
                taskService.addTask(new OrderUnpaidTask(order.getId(), delay));
            }
        }

        // 从数据库捞出未确认售卖订单
        List<LitemallOrderItem> saleList = orderService.querySaleUnconfirm();
        for (LitemallOrderItem orderItem : saleList) {
            LocalDateTime add = orderItem.getShipTime();
            LocalDateTime now = LocalDateTime.now();
            if(add==null){
                continue;
            }
            LocalDateTime expire =  add.plusDays(SystemConfig.getOrderUnconfirm());
            if(expire.isBefore(now)) {
                // 已经过期，则加入延迟队列
                logger.debug("已经过期，则加入延迟队列 延迟为0");
                taskService.addTask(new OrderUnconfirmTask(orderItem.getId(), 0));
            }
            else{
                // 还没过期，则加入延迟队列
                long delay = ChronoUnit.MILLIS.between(now, expire);
                logger.debug("还没过期，则加入延迟队列 延迟为" + delay);
                taskService.addTask(new OrderUnconfirmTask(orderItem.getId(), delay));
            }
        }
    }
}